from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
import time
import os
import requests
import platform
from enum import Enum, auto

class OSConfig:
    """操作系统配置类"""
    class OSType(Enum):
        WINDOWS = auto()
        LINUX = auto()
    
    @staticmethod
    def get_os_type():
        """获取当前操作系统类型"""
        return OSConfig.OSType.LINUX if platform.system() == 'Linux' else OSConfig.OSType.WINDOWS

    @staticmethod
    def get_chrome_options():
        """获取Chrome浏览器选项"""
        options = webdriver.ChromeOptions()
        options.add_argument("--disable-blink-features=AutomationControlled")
        options.add_experimental_option("excludeSwitches", ["enable-automation"])
        
        if OSConfig.get_os_type() == OSConfig.OSType.LINUX:
            options.add_argument("--headless")
            options.add_argument("--no-sandbox")
            options.add_argument('--disable-gpu')  # 禁用 GPU 加速
            options.add_argument("--disable-dev-shm-usage")
        else:
            options.add_argument("--headless")
            
        return options

def get_real_page(url):
    """获取渲染后的页面源码"""
    options = webdriver.ChromeOptions()
    options.add_argument("--headless")  # 无头模式，不显示浏览器窗口
    options.add_argument("--disable-blink-features=AutomationControlled")  # 绕过反爬检测
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    
    driver = webdriver.Chrome(
        service=Service(ChromeDriverManager().install()),
        options=OSConfig.get_chrome_options()  # 使用统一配置
    )
    
    try:
        driver.get(url)
        time.sleep(5)  # 强制等待5秒
        page_source = driver.page_source
        return page_source
    finally:
        driver.quit()
        


class DouyinDownloader:
    """抖音视频下载器"""
    last_downloaded_filename = None
    
    def __init__(self):
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0',
            'Referer': 'https://www.douyin.com/',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Accept-Encoding': 'gzip, deflate, br',
            'Connection': 'keep-alive',
            'Upgrade-Insecure-Requests': '1'
        }
        
        
    def download(self, url, filename, save_dir='.'):
        """
        下载抖音视频
        
        参数:
            url (str): 视频URL
            save_dir (str): 保存目录，默认为当前目录
        """
        try:
            if not os.path.exists(save_dir):
                os.makedirs(save_dir)
                
            save_path = os.path.join(save_dir, filename)
            
            print(f"开始下载: {url}")
            with requests.Session() as session:
                # 先发送HEAD请求获取信息
                head_resp = session.head(url, headers=self.headers, allow_redirects=True)
                head_resp.raise_for_status()
                
                # 正式下载
                response = session.get(url, headers=self.headers, stream=True, timeout=30)
                response.raise_for_status()
                
                # 获取文件大小
                file_size = int(response.headers.get('content-length', 0))
                print(f"文件大小: {file_size/1024/1024:.2f}MB")
                
                # 写入文件
                with open(save_path, 'wb') as f:
                    for chunk in response.iter_content(chunk_size=8192):
                        f.write(chunk)
                
                self.last_downloaded_filename = os.path.abspath(save_path)
                print(f"视频已保存到: {self.last_downloaded_filename}")
                return True
                
        except Exception as e:
            print(f"下载失败: {str(e)}")
            return False
